package com.jojo;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.watch.WatchMonitor;
import cn.hutool.core.io.watch.Watcher;
import cn.hutool.core.io.watch.watchers.DelayWatcher;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.java.Log;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.WatchEvent;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicBoolean;

@Log
public class FileWatcherApplication {
    private static final String dir;
    private static final String git;
    private static final Semaphore semaphore = new Semaphore(1);
    private static final AtomicBoolean flag = new AtomicBoolean(true);
    private static final Map<String, Boolean> marks = new HashMap<>();
    //启动自动加载，dir和git的配置
    static {
        JSONObject config = JSONUtil.parseObj(FileUtil.readUtf8String("config.json"));
        dir = config.get("dir", String.class);
        git = config.get("git", String.class);
    }
    public static void main(String[] args) {
        update();
        addWatcher(dir);
        loadFile(new File(dir));
    }
    /**
     * 对指定文件添加监视器
     * @param file
     * @return void
     * @author huang_qiu_sheng
     * @date 3/30/2021 2:02 PM
     */
    public static void loadFile(File file){
        if (file.isDirectory()){
            File[] childrenFiles = file.listFiles();
            if (childrenFiles  == null || childrenFiles .length == 0){ return;}
            for (File childFile : childrenFiles){
                if (childFile.isDirectory()){
                    loadFile(childFile);
                }else{
                    addWatcher(file.getAbsolutePath());
                }
            }
        }
    }
    /**
     * 添加监视器
     * @param path
     * @return void
     * @author huang_qiu_sheng
     * @date 3/30/2021 1:59 PM
     */
    public static void addWatcher(String path) {
        if(marks.containsKey(path)||path.contains(".git")){
            return;
        }
        marks.put(path, true);
        Watcher watcher = new Watcher() {
            @Override
            public void onCreate(WatchEvent<?> event, Path currentPath) {
                tryUpdate("onCreate in path:"+currentPath);
            }

            @Override
            public void onModify(WatchEvent<?> event, Path currentPath) {
                tryUpdate("onModify in path:"+currentPath);
            }

            @Override
            public void onDelete(WatchEvent<?> event, Path currentPath) {
                tryUpdate("onDelete in path:"+currentPath);
            }

            @Override
            public void onOverflow(WatchEvent<?> event, Path currentPath) {
                log.warning("onOverflow in path:"+currentPath);
            }
        };
        WatchMonitor monitor = WatchMonitor.createAll(path, new DelayWatcher(watcher, 500));
        monitor.start();
    }
    /**
     * 尝试更新数据
     * @param print
     * @return void
     * @author huang_qiu_sheng
     * @date 3/30/2021 2:50 PM
     */
    public static void tryUpdate(String print){
        if (flag.get()&&semaphore.tryAcquire()) {
            log.info(print);
            update();
            loadFile(new File(dir));
            //使用一个线程挂起flag，使其值在一段时间内无法改变
            new Thread(()->{
                flag.set(false);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                flag.set(true);
            }).start();
            semaphore.release();
        }
    }
    /**
     *
     * @param
     * @return void
     * @author huang_qiu_sheng
     * @date 3/30/2021 12:51 PM
     */
    public static void update(){
        String prefix = "cmd.exe /c cd "+dir+" && ";
        //检查是否存在，如果存在就创建文件夹
        Path path = Paths.get(dir);
        if(!Files.exists(path)){
            exec("cmd.exe /c cd "+path.getParent()+" && git clone "+git);
        }
//        exec(prefix+"git pull ");
        exec(prefix+"git add . ");
        exec(prefix+"git commit -m \"更新数据\" . ");
        exec(prefix+"git push origin");
    }
    /**
     * 执行cmd的命令
     * @param cmd
     * @return void
     * @author huang_qiu_sheng
     * @date 3/30/2021 12:50 PM
     */
    public static void exec(String cmd){
        try {
            Process process = Runtime.getRuntime().exec(cmd);
            doWaitFor(process);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 避免runtime 在运行结束后，仍然堵塞
     * 代码来源：https://www.jb51.net/article/55450.htm
     * @param process
     * @return int
     * @author huang_qiu_sheng
     * @date 3/16/2021 12:05 PM
     */
    public static int doWaitFor(Process process) {
        InputStream in = null;
        InputStream err = null;
        int exitValue = -1; // returned to caller when p is finished
        try {
            in = process.getInputStream();
            err = process.getErrorStream();
            boolean finished = false; // Set to true when p is finished
            while (!finished) {
                try {
                    while (in.available() > 0) {
                        // Print the output of our system call
                        Character c = new Character((char) in.read());
                        System.out.print(c);
                    }
                    while (err.available() > 0) {
                        // Print the output of our system call
                        Character c = new Character((char) err.read());
                        System.out.print(c);
                    }
                    exitValue = process.exitValue();
                    finished = true;
                } catch (IllegalThreadStateException e) {
                    Thread.sleep(500);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (err != null) {
                try {
                    err.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return exitValue;
    }
}
